/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.lcfgly.Interceptor;

import com.lcfgly.Database.UserInfo;
import com.lcfgly.util.ConfigDate;
import com.lcfgly.util.WybEncode;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 登入控制
 * @author lcfgly
 */
public class LoginInterceptor extends HandlerInterceptorAdapter{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        UserInfo session=(UserInfo)request.getSession().getAttribute("logininfo");
        Integer x=(Integer)request.getSession().getAttribute("shopperfect");
        if(session == null || session.getUid()==null || session.getUsername() == null){
            // 未登录  
            PrintWriter out = response.getWriter();
            StringBuilder builder = new StringBuilder();
            builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
            builder.append("window.top.location.href=\"");
            builder.append(ConfigDate.config("loginurl"));
            builder.append("\";</script>");
            out.print(builder.toString());
            out.close();
            return false;
        }else{
            if(x != null && x==0){
                StringBuilder s=new StringBuilder().append("uid=").append(session.getUid()).append("&").append("username=").append(session.getUsername())
                        .append("&").append("uname=").append(session.getUname());
                Cookie cook=new Cookie("SESSION", WybEncode.encode(s.toString()));
                cook.setPath("/");
                cook.setMaxAge(86400);
                response.addCookie(cook);
                PrintWriter out = response.getWriter();
                StringBuilder builder = new StringBuilder();
                builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
                builder.append("window.top.location.href=\"");
                builder.append(ConfigDate.config("shopperfect"));
                builder.append("\";</script>");
                out.print(builder.toString());
                out.close();
                return false;
            }
            return super.preHandle(request, response, handler); 
        }
    }
    
}
